#include "PolyStepCurveParser.h"

#include "BoolParser.h"
#include "DoubleParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PolyStepCurveParser::PolyStepCurveParser(
    DoubleParser *&_xParser
    , DoubleParser *&_yParser
    , DoubleParser *&_centerXParser
    , DoubleParser *&_centerYParser
    , BoolParser *&_clockwiseParser
):    m_xParser(_xParser)
    , m_yParser(_yParser)
    , m_centerXParser(_centerXParser)
    , m_centerYParser(_centerYParser)
    , m_clockwiseParser(_clockwiseParser)
{

}

bool PolyStepCurveParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new PolyStepCurve());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("x")))
    {
        data = reader->attributes().value(QStringLiteral("x"));
        if (!m_xParser->parse(reader, data))
            return false;
        m_result->x = m_xParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("x: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("y")))
    {
        data = reader->attributes().value(QStringLiteral("y"));
        if (!m_yParser->parse(reader, data))
            return false;
        m_result->y = m_yParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("y: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("centerX")))
    {
        data = reader->attributes().value(QStringLiteral("centerX"));
        if (!m_centerXParser->parse(reader, data))
            return false;
        m_result->centerX = m_centerXParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("centerX: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("centerY")))
    {
        data = reader->attributes().value(QStringLiteral("centerY"));
        if (!m_centerYParser->parse(reader, data))
            return false;
        m_result->centerY = m_centerYParser->result();
    }
    else
    {
        reader->raiseError(QStringLiteral("centerY: Attribute is required"));
        return false;
    }
    if (reader->attributes().hasAttribute(QStringLiteral("clockwise")))
    {
        data = reader->attributes().value(QStringLiteral("clockwise"));
        if (!m_clockwiseParser->parse(reader, data))
            return false;
        m_result->clockwiseOptional = Optional<Bool>(m_clockwiseParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

PolyStepCurve *PolyStepCurveParser::result()
{
    return m_result.take();
}

}